package cn.com.idmy.cloud.util;


import lombok.Getter;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class SpringUtil implements ApplicationContextAware {
    @Getter
    private static ApplicationContext applicationContext;

    @SuppressWarnings("unchecked")
    public static <T> T getBean(@NotNull String name) throws BeansException {
        return (T) applicationContext.getBean(name);
    }

    public static <T> T getBean(@NotNull Class<T> type) throws BeansException {
        return applicationContext.getBean(type);
    }

    public static <T> T getBean(@NotNull String beanName, @NotNull Class<T> type) throws BeansException {
        return applicationContext.getBean(beanName, type);
    }

    @NotNull
    public static <T> Map<String, T> getBeansOfType(@NotNull Class<T> clazz) {
        return applicationContext.getBeansOfType(clazz);
    }

    public static void publishEvent(@NotNull Object event) {
        applicationContext.publishEvent(event);
    }

    public void setApplicationContext(@NotNull ApplicationContext ctx) throws BeansException {
        applicationContext = ctx;
    }
}
